INCLUDE("@CMAKE_SOURCE_DIR@/cmake/ToNativePath.cmake")

SET(MINGW "@MINGW@")
SET(STAGING_DIR "@CMAKE_BINARY_DIR@/staging")
FILE(REMOVE_RECURSE "${STAGING_DIR}")
FILE(MAKE_DIRECTORY "${STAGING_DIR}")

# Translations
SET(QM_FILES "@QM_FILES@")
FOREACH(file ${QM_FILES})
	GET_FILENAME_COMPONENT(fname "${file}" NAME)
	CONFIGURE_FILE("${file}" "${STAGING_DIR}/translations/${fname}" COPYONLY)
ENDFOREACH()

# Imageformat plugins for Qt
FILE(GLOB imageformat_plugins "${CONF_BUILD_DIR}/imageformats/*.dll")
FOREACH(file ${imageformat_plugins})
	GET_FILENAME_COMPONENT(fname "${file}" NAME)
	CONFIGURE_FILE("${file}" "${STAGING_DIR}/imageformats/${fname}" COPYONLY)
	IF(MINGW)
		EXECUTE_PROCESS(COMMAND "@CMAKE_STRIP@" "${STAGING_DIR}/imageformats/${fname}")
	ENDIF()
ENDFOREACH()

# Extra binaries (DLLs)
SET(COPY_TO_STAGING_DIR_Debug "@COPY_TO_BUILD_DIR_Debug@")
SET(COPY_TO_STAGING_DIR_Release "@COPY_TO_BUILD_DIR_Release@")
SET(COPY_TO_STAGING_DIR_MinSizeRel "@COPY_TO_BUILD_DIR_MinSizeRel@")
SET(COPY_TO_STAGING_DIR_RelWithDebInfo "@COPY_TO_BUILD_DIR_RelWithDebInfo@")
SET(EXTRA_BINARIES ${COPY_TO_STAGING_DIR_${CFG}})

# These are passed at runtime, not at configure time.
SET(EXECUTABLES "${SCANTAILOR_EXE}" "${SCANTAILOR_CLI_EXE}" "${CRASHREPORTER_EXE}")

# Strip executables and DLLs.
FOREACH(src_file ${EXECUTABLES} ${EXTRA_BINARIES})
	SET(subdir "")
	IF(src_file MATCHES ".*=>.*")
		STRING(REGEX REPLACE ".*=>(.*)" "/\\1" subdir "${src_file}")
		STRING(REGEX REPLACE "(.*)=>.*" "\\1" src_file "${src_file}")
	ENDIF()
	GET_FILENAME_COMPONENT(fname "${src_file}" NAME)
	SET(dst_file "${STAGING_DIR}${subdir}/${fname}")
	
	CONFIGURE_FILE("${src_file}" "${dst_file}" COPYONLY)
	IF(MINGW AND fname MATCHES ".*\\.(([Dd][Ll][Ll])|([Ee][Xx][Ee]))$")
		MESSAGE(STATUS "Stripping ${dst_file}")
		EXECUTE_PROCESS(COMMAND "@CMAKE_STRIP@" "${dst_file}")
	ENDIF()
ENDFOREACH()

# Microsoft CRT redistributable
IF(CRT_REDIST_PATH)
	GET_FILENAME_COMPONENT(CRT_REDIST_DIR "${CRT_REDIST_PATH}" NAME)
	EXECUTE_PROCESS(
		COMMAND "${CMAKE_COMMAND}" -E copy_directory
		"${CRT_REDIST_PATH}" "${STAGING_DIR}/${CRT_REDIST_DIR}"
	)
ENDIF()
